package com.gzlg.hospital.controller;

import com.gzlg.hospital.pojo.*;
import com.gzlg.hospital.pojo.query.hQuery;
import com.gzlg.hospital.service.DoctorService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class DoctorController {
    @Autowired
    private DoctorService doctorService;
    //医生首页
    @GetMapping("/DoctorIndex")
    public String Doctor(HttpSession session) {
        Doctor doctor = (Doctor) session.getAttribute("user");
        return "Doctor/doctorIndex";
    }
    //个人信息
    @GetMapping("/Doctor/resume")
    public String DoctorResume(Integer id, Model model, HttpSession session) {
        Doctor doctor = (Doctor) session.getAttribute("user");
        model.addAttribute("doctor",doctorService.getDoctorById(doctor.getId()));
        return "Doctor/resume";
    }
    //待处理病历
    @GetMapping("/Doctor/appointmentDetails")
    public String listAppointmentDetailsByDoctorId(HttpSession  session, Model model,hQuery hQuery){
        Doctor doctor = (Doctor) session.getAttribute("user");
        model.addAttribute("page",doctorService.listAppointmentDetailsByDoctorId(doctor.getId(), hQuery));
        return "Doctor/appointment_details";
    }
    //根据挂号ID查处理病历
    @GetMapping("/Doctor/appointmentDetailsByRegistrationId")
    public String listAppointmentDetailsByIdDoctorId(HttpSession  session, Model model,@RequestParam Integer registration_id, hQuery hQuery) {
        Doctor doctor = (Doctor) session.getAttribute("user");
        Map<String, Integer> map = new HashMap<>();
        map.put("registration_id",registration_id);
        map.put("doctor_id",doctor.getId());
        model.addAttribute("page",doctorService.listAppointmentDetailsByRegistrationIdDoctorId(map, hQuery));
        return "Doctor/appointment_details";
    }
    //医生查看全部病历
    @GetMapping("/Doctor/medicalRecord")
    public String listMedicalRecord(HttpSession session, Model model,hQuery hquery) {
        Doctor doctor = (Doctor) session.getAttribute("user");
        if (doctor != null) {
            model.addAttribute("page",doctorService.listMedicalRecord(hquery));
            return "Doctor/medical_record";
        }else return "redirect:/login";
    }
    //医生查看指定患者病历
    @GetMapping("/Doctor/medicalRecordByPatientId")
    public String listMedicalRecordByPatientId(Model model,hQuery hquery, @RequestParam Integer patient_id) {
        model.addAttribute("page",doctorService.listMedicalRecordByPatientId(patient_id, hquery));
        return "Doctor/medical_record";
    }
    //护士查看待处理挂号
    @GetMapping("/Doctor/registration")
    public String listRegistration(HttpSession session, Model model,hQuery hQuery) {
        Doctor doctor = (Doctor) session.getAttribute("user");
        if (doctor != null) {
            model.addAttribute("page",doctorService.listRegistration(hQuery));
            return "Doctor/nurseRegistration";
        }else return "redirect:/login";
    }
    //护士处理挂号
    @GetMapping("/Doctor/gotoRegistration")
    public String gotoRegistration(
            Model model,
            @RequestParam(required = false) Integer registration_id,
            @RequestParam(required = false) Integer patient_id,
            @RequestParam(required = false) String department) {

        if (registration_id == null || patient_id == null) {
            return "redirect:/some-error-page";
        }

        try {
            Patient patient = doctorService.getPatientById(patient_id);
            Registration registration = doctorService.getRegistrationById(registration_id);

            model.addAttribute("patient", patient);
            model.addAttribute("registration", registration);
            model.addAttribute("department", department);

            // 不管用户是否选择了科室，都加载两个房间号列表
            List<Consultation_room> internalRooms = doctorService.getRoomsByDepartment("内科");
            List<Consultation_room> surgeryRooms = doctorService.getRoomsByDepartment("外科");

            model.addAttribute("internalRooms", internalRooms);
            model.addAttribute("surgeryRooms", surgeryRooms);

        } catch (NumberFormatException e) {
            return "redirect:/some-error-page";
        }

        return "Doctor/nurseDepartment";
    }

    //护士开始处理挂号
    @PostMapping("/Doctor/updateRegistration")
    public String updateRegistration(
            RedirectAttributes redirectAttributes,
            @RequestParam Integer id,
            @RequestParam Integer doctor_id,
            @RequestParam String department,
            @RequestParam(required = false) String remark,
            @RequestParam Integer patient_id,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm") Date treatment_time,
            @RequestParam(required = false) String internal_room,
            @RequestParam(required = false) String surgery_room) {

        String treatment_room = department.equals("内科") ? internal_room : surgery_room;
        if (id == null || doctor_id == null || patient_id == null || treatment_room == null || treatment_room.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "请填写所有必填项");
            return "redirect:/Doctor/gotoRegistration?registration_id=" + id + "&patient_id=" + patient_id + "&department=" + department;
        }

        Appointment_details appointment_details = new Appointment_details();
        appointment_details.setRegistration_id(id);
        appointment_details.setPatient_id(patient_id);
        appointment_details.setDoctor_id(doctor_id);
        appointment_details.setRoom_number(treatment_room);
        appointment_details.setDoctor_name(doctorService.getDoctorById(doctor_id).getName());
        appointment_details.setTreatment_time(treatment_time);
        appointment_details.setCreate_date(new Date());
        appointment_details.setStatus("待处理");

        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("remark", remark);
        map.put("room", treatment_room);
        map.put("doctor_id", doctor_id);
        map.put("department", department);

        if (doctorService.updateRegistration(map)) {
            doctorService.addAppointmentDetails(appointment_details);
            redirectAttributes.addFlashAttribute("message", "处理成功");
        } else {
            redirectAttributes.addFlashAttribute("message", "处理失败");
        }

        redirectAttributes.addAttribute("registration_id", id);
        redirectAttributes.addAttribute("patient_id", patient_id);
        return "redirect:/Doctor/gotoRegistration";
    }

    @GetMapping("/Doctor/addMedicalRecord")
    public String  addMedicalRecord(Model model,@RequestParam Integer patient_id,@RequestParam Integer registration_id){
        Patient patient = doctorService.getPatientById(patient_id);
        Registration registration = doctorService.getRegistrationById(registration_id);
        model.addAttribute("patient",patient);
        model.addAttribute("registration",registration);
        return "Doctor/doappointment";
    }
    @PostMapping("/Doctor/addMedicalRecord")
    public String  addMedicalRecord(HttpSession session,
                                    @RequestParam String treatment_plan
                                    ,@RequestParam(required = false) LocalDateTime next_visit_date ,
                                    @RequestParam String diagnosis,
                                    @RequestParam Integer registration_id,
                                    @RequestParam Integer patient_id,
                                    RedirectAttributes redirectAttributes){
        Doctor doctor = (Doctor) session.getAttribute("user");
        Medical_record medical_record = new Medical_record();
        medical_record.setRegistration_id(registration_id);
        medical_record.setDiagnosis(diagnosis);
        medical_record.setDoctor_id(doctor.getId());
        medical_record.setTreatment_plan(treatment_plan);
        medical_record.setPatient_id(patient_id);
        if (next_visit_date != null){
            medical_record.setNext_visit_date(next_visit_date);
            if(doctorService.addMedicalRecord(medical_record)){
                doctorService.updateAppointmentDetails(registration_id);
                doctorService.updateRegistrationStatus(registration_id);
                redirectAttributes.addFlashAttribute("message","提交成功");
                return "redirect:/Doctor/addMedicalRecord?patient_id=" + patient_id + "&registration_id=" + registration_id;
            }else{
                redirectAttributes.addFlashAttribute("message","提交失败");
                return "redirect:/Doctor/addMedicalRecord?patient_id=" + patient_id + "&registration_id=" + registration_id;
            }
        }else {
            medical_record.setNext_visit_date(null);
            if(doctorService.addMedicalRecord2(medical_record)){
                doctorService.updateAppointmentDetails(registration_id);
                doctorService.updateRegistrationStatus(registration_id);
                redirectAttributes.addFlashAttribute("message","提交成功");
                return "redirect:/Doctor/addMedicalRecord?patient_id=" + patient_id + "&registration_id=" + registration_id;
            }else{
                redirectAttributes.addFlashAttribute("message","提交失败");
                return "redirect:/Doctor/addMedicalRecord?patient_id=" + patient_id + "&registration_id=" + registration_id;
            }
        }
    }
}
